package repository

import (
	"gorm.io/gorm"
	"niu-video/app/model"
	"niu-video/pkg/db"
)

var UserRepository = newUserRepository()

func newUserRepository() *userRepository {
	return &userRepository{}
}

type userRepository struct {
	baseRepository
}

// Get 通过 ID 获取用户
func (u *userRepository) Get(id int64) (userModel model.User) {
	db.DB.Where("user_id", id).First(&userModel)
	return
}

func (u *userRepository) GetBy(column string, value string) (userModel model.User) {
	db.DB.Where(column, value).First(&userModel)
	return
}

func (u *userRepository) Save(user *model.User) (err error) {
	err = db.DB.Save(user).Error
	return err
}

// All 获取所有用户数据
func (u *userRepository) All() (users []model.User) {
	db.DB.Find(&users)
	return
}

func (u *userRepository) GetByUserIds(ids []int64) (users []model.User) {
	db.DB.Where("user_id IN ?", ids).Find(&users)
	return
}

// 修改关注人数
func (u *userRepository) UpdateUserFollowCount(userId int64, cnt int64) {
	db.DB.Model(&model.User{}).Where("user_id = ?", userId).Update("follow_count", gorm.Expr("follow_count + ?", cnt))
}

func (u *userRepository) UpdateUser(request model.UpdateUserInfoRequest, userId int64) error {
	err := db.DB.Model(&model.User{}).Where("user_id = ?", userId).
		Update("username", request.Username).
		Update("avatar", request.Avatar).
		Update("nickname", request.Nickname).
		Update("signature", request.Signature).Error
	return err
}
